// DeepSeek AI服务适配器
const AIServiceBase = require('./AIServiceBase');
const axios = require('axios');

class DeepseekService extends AIServiceBase {
  constructor(config) {
    super(config);
    this.client = axios.create({
      baseURL: config.endpoint,
      timeout: config.timeout || 30000,
      headers: this.buildHeaders()
    });
  }
  
  /**
   * 构建请求头
   * @returns {Object} 请求头
   */
  buildHeaders() {
    const headers = super.buildHeaders();
    if (this.config.apiKey) {
      headers['Authorization'] = `Bearer ${this.config.apiKey}`;
    }
    return headers;
  }
  
  /**
   * 发送聊天消息
   * @param {Array} messages - 消息数组
   * @param {Object} options - 额外选项
   * @returns {Promise<Object>} AI响应
   */
  async chat(messages, options = {}) {
    try {
      const requestData = {
        model: options.model || this.config.model,
        messages: this.formatMessages(messages),
        max_tokens: options.maxTokens || this.config.maxTokens,
        temperature: options.temperature || this.config.temperature,
        stream: false
      };
      
      // 添加可选参数
      if (options.topP !== undefined) requestData.top_p = options.topP;
      if (options.frequencyPenalty !== undefined) requestData.frequency_penalty = options.frequencyPenalty;
      if (options.presencePenalty !== undefined) requestData.presence_penalty = options.presencePenalty;
      
      const response = await this.client.post('', requestData);
      
      return this.parseResponse(response.data);
    } catch (error) {
      this.handleError(error, 'chat');
    }
  }
  
  /**
   * 流式聊天
   * @param {Array} messages - 消息数组
   * @param {Object} options - 额外选项
   * @returns {AsyncGenerator} 流式响应
   */
  async *chatStream(messages, options = {}) {
    try {
      const requestData = {
        model: options.model || this.config.model,
        messages: this.formatMessages(messages),
        max_tokens: options.maxTokens || this.config.maxTokens,
        temperature: options.temperature || this.config.temperature,
        stream: true
      };
      
      const response = await this.client.post('', requestData, {
        responseType: 'stream'
      });
      
      for await (const chunk of this.parseStream(response.data)) {
        yield chunk;
      }
    } catch (error) {
      this.handleError(error, 'chatStream');
    }
  }
  
  /**
   * 格式化消息
   * @param {Array} messages - 原始消息数组
   * @returns {Array} 格式化后的消息数组
   */
  formatMessages(messages) {
    return messages.map(msg => ({
      role: msg.role,
      content: msg.content
    }));
  }
  
  /**
   * 解析响应
   * @param {Object} data - 响应数据
   * @returns {Object} 解析后的响应
   */
  parseResponse(data) {
    if (!data.choices || !data.choices[0]) {
      throw new Error('Invalid response format from DeepSeek API');
    }
    
    const choice = data.choices[0];
    
    return {
      id: data.id,
      content: choice.message?.content || '',
      role: choice.message?.role || 'assistant',
      finishReason: choice.finish_reason,
      usage: data.usage,
      model: data.model,
      timestamp: new Date().toISOString()
    };
  }
  
  /**
   * 解析流式响应
   * @param {Stream} stream - 流对象
   * @returns {AsyncGenerator} 解析后的数据块
   */
  async *parseStream(stream) {
    const decoder = new TextDecoder();
    let buffer = '';
    
    for await (const chunk of stream) {
      buffer += decoder.decode(chunk, { stream: true });
      
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';
      
      for (const line of lines) {
        const trimmedLine = line.trim();
        
        if (trimmedLine === '') continue;
        if (trimmedLine === 'data: [DONE]') return;
        
        if (trimmedLine.startsWith('data: ')) {
          try {
            const jsonData = JSON.parse(trimmedLine.slice(6));
            
            if (jsonData.choices && jsonData.choices[0]) {
              const choice = jsonData.choices[0];
              
              if (choice.delta && choice.delta.content) {
                yield {
                  content: choice.delta.content,
                  finishReason: choice.finish_reason,
                  timestamp: new Date().toISOString()
                };
              }
            }
          } catch (error) {
            console.warn('[DeepSeek] Failed to parse stream chunk:', error.message);
          }
        }
      }
    }
  }
  
  /**
   * 检查服务是否可用
   * @returns {Promise<boolean>} 是否可用
   */
  async isAvailable() {
    try {
      // 简单的模型列表查询来测试连接
      const response = await this.client.get('/models', {
        timeout: 10000
      });
      
      return response.status === 200;
    } catch (error) {
      // 如果模型列表接口不可用，尝试简单的聊天测试
      try {
        const testResponse = await this.chat([
          { role: 'user', content: 'ping' }
        ], { maxTokens: 5 });
        
        return !!testResponse.content;
      } catch (chatError) {
        return false;
      }
    }
  }
}

module.exports = DeepseekService;